package com.study.websocket;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.*;
import io.netty.util.concurrent.EventExecutorGroup;

public class WsIndexPageHandler extends SimpleChannelInboundHandler<FullHttpRequest> {
    private final String websocketPath;
    public WsIndexPageHandler(String websocketPath) {
        this.websocketPath = websocketPath;
    }

    protected void channelRead0(ChannelHandlerContext ctx, FullHttpRequest req) throws Exception {
        // 处理错误或无法解析的http请求

        if (!req.decoderResult().isSuccess()) {
            send("无法处理的请求", ctx, HttpResponseStatus.BAD_REQUEST);
            return;
        }
        if (!req.getMethod().equals(HttpMethod.GET)) {
            // 只允许GET请求
            send("只允许GET请求", ctx, HttpResponseStatus.FORBIDDEN);
            return;
        }
        if ("/".equalsIgnoreCase(req.getUri()) || "/index.html".equalsIgnoreCase(req.getUri())) {
            // 生成websocket地址，写入index页面中
            String websocketLocation = getWebSocketLocation(ctx.pipeline(), req, websocketPath);
            System.out.println("websocketLocation = " + websocketLocation);
            send("无法解析", ctx, HttpResponseStatus.NOT_FOUND);
            // 生成index页面的具体内容并送往浏览器
            ByteBuf content = MakeIndexPage.getContent();
            DefaultHttpResponse response =
                    new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK, content);
            HttpUtil.setContentLength(response, content.readableBytes());
            response.headers().set("Content-Type", "text/html;charset=UTF-8");
            ctx.writeAndFlush(response).addListener(ChannelFutureListener.CLOSE);
        } else {
            send("无法解析", ctx, HttpResponseStatus.NOT_FOUND);
        }
    }

    private void send(String msg, ChannelHandlerContext ctx, HttpResponseStatus status) {
        FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, status,
                Unpooled.copiedBuffer(msg.getBytes()));
        response.headers().set(HttpHeaderNames.ACCEPT, "*")
                .set(HttpHeaderNames.CONTENT_TYPE, "text/plain;charset=UTF-8");
        ctx.writeAndFlush(response).addListener(ChannelFutureListener.CLOSE); // .sync();
    }
}
